﻿using System;
using System.Linq;

using Infrastructure.NetExtensions;
using TempEmployees.DAL;
using TempEmployees.BLL.EntitiesExtensions;
using TempEmployees.BLL.Database;

namespace TempEmployees.Web
{
    public partial class WebForm6 : ABasePage
    {
        private int RadioButtonListSearch
        {
            set
            {
                if (value == 0) RadioByID.Checked = true;
                else if (value == 1) RadioByFilters.Checked = true;
            }
            get
            {
                if (RadioByID.Checked) return 0;
                else return 1;
            }
        }

        private int ActivatedID
        {
            set { Session.Set<int>("ActivatedID", value); }
            get { return Session.Get<int>("ActivatedID"); }
        }

        private bool IsActivated
        {
            set { Session.Set<bool>("IsActivated", value); }
            get { return Session.Get<bool>("IsActivated"); }
        }

        protected override void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            //page defualt button
            Page.Form.DefaultButton = ButtonSearch.UniqueID;
            //gridview delegate
            GridViewAssignments1.GotoAssignmentDetailes = GotoAssignmentDetailes;
            
            if (!IsPostBack)
            {
                SetDropDownLists();
                if (!APageData.Exist<SearchAssignmentsStoreData>())
                {
                    InitDropDownList();  
                }
                else
                {
                    RetrieveData();
                }
                RadioButtonListSearch = 1;
                SetGridView();
            }
            SetAfterAssignmentUpdate();
        }

        private void SetGridView()
        {
            if (RadioButtonListSearch == 0) //search by employee ID
            {
                int assignmentId;
                if (int.TryParse(TextBoxSearchId.Text, out assignmentId) && EAssignment.GetAssignmentById(assignmentId) != null)
                {
                    GotoAssignmentDetailes(assignmentId);
                }
                return;
            }

            Filters filters = new Filters();

            //if employer - need to see only his employees
            if (State.UserRole == DbConstants.Roles.Employer)
            {
                filters.Add("UserID", State.UserId);
            }

            if (DropDownListUsers.SelectedIndex != 0 && State.UserRole != DbConstants.Roles.Employer)
            {
                filters.Add("UserID", int.Parse(DropDownListUsers.SelectedValue));
            }
            bool allowShowNotActive = true;
            if (DropDownListStatus.SelectedIndex != 0)
            {
                filters.Add("StatusID", int.Parse(DropDownListStatus.SelectedValue));
                allowShowNotActive = false;
            }
            if (DropDownListBudgetTypes.SelectedIndex != 0)
            {
                filters.Add("Budget.TypeID", int.Parse(DropDownListBudgetTypes.SelectedValue));
            }
            
            GridViewAssignments1.SetGridView(filters, allowShowNotActive);
        }

        private void InitDropDownList()
        {
            if (Session[SessionState.SESSION_STATE] == null) return;
            DbConstants.Roles role = ((SessionState)Session[SessionState.SESSION_STATE]).UserRole;
            switch (role)
            {
                case DbConstants.Roles.Secretary:
                    DropDownListStatus.SelectedValue = ((int)DbConstants.Status.Approved).ToString();
                    break;
                case DbConstants.Roles.HeadDepartment:
                    DropDownListStatus.SelectedValue = ((int)DbConstants.Status.Pending).ToString();
                    break;
                default:
                    DropDownListStatus.SelectedIndex = 0;
                    break;
            }
        }
            
        private void SetDropDownLists()
        {
            DbServices.SetDropDownBudgetTypes(DropDownListBudgetTypes);

            DbServices.SetDropDownStatus(DropDownListStatus);

            DbServices.SetDropDownUsers(DropDownListUsers);

            if (State.UserRole == DbConstants.Roles.Employer)
            {
                DropDownListUsers.Visible = false;
                LabelEmployer.Visible = false;
            }
        }

        protected void ButtonSearch_Click(object sender, EventArgs e)
        {
            SetGridView();
        }

        private void GotoAssignmentDetailes(int assignmentId)
        {
            APageData.Set(new SearchAssignmentsStoreData(DropDownListStatus.SelectedIndex,
                DropDownListUsers.SelectedIndex, DropDownListBudgetTypes.SelectedIndex));

            APageData.Set(new AssignmentDetailsPageData(assignmentId, GUIServices.PAGE_SEARCH_ASSIGNMENTS));

            Response.Redirect(GUIServices.PAGE_UPDATE_ASSIGNMENT);
        }

        private void RetrieveData()
        {
            SearchAssignmentsStoreData data = APageData.Get<SearchAssignmentsStoreData>();

            DropDownListBudgetTypes.SelectedIndex = data.DropDownBudgetTypeIndex;
            DropDownListStatus.SelectedIndex = data.DropDownStatusIndex;
            DropDownListUsers.SelectedIndex = data.DropDownUsersIndex;

            data.Remove();
        }

        private void SetAfterAssignmentUpdate()
        {
            if (!APageData.Exist<UpdatedAssignmentData>())
            {
                if (!IsActivated) PanelUpdateMessage.Visible = false;
                return;
            }
            UpdatedAssignmentData data = APageData.Get<UpdatedAssignmentData>();
            PanelUpdateMessage.Visible = true;
            LabelAssignmentId.Text = "מספר העסקה " + data.AssignmentId;
            switch (data.UpdateType)
            {
                case UpdatedAssignmentData.eUpdateType.New:
                    LabelUpdateMessage.Text = WebConfigData.MESSAGE_ASSIGNMENT_SUBMITTED;
                    break;
                case UpdatedAssignmentData.eUpdateType.Update:
                    LabelUpdateMessage.Text = WebConfigData.MESSAGE_ASSIGNMENT_UPDATED;
                    break;
                case UpdatedAssignmentData.eUpdateType.Approved:
                    LabelUpdateMessage.Text = WebConfigData.MESSAGE_ASSIGNMENT_APPROVED;
                    break;
                case UpdatedAssignmentData.eUpdateType.Activated:
                    LabelUpdateMessage.Text = WebConfigData.MESSAGE_ASSIGNMENT_ACTIVATED;
                    ProduceFormTimer.Enabled = true;
                    if (!IsActivated) ActivatedID = data.AssignmentId;
                    break;
                case UpdatedAssignmentData.eUpdateType.Rejected:
                    LabelUpdateMessage.Text = WebConfigData.MESSAGE_ASSIGNMENT_REJECTED;
                    break;
            }
            if (data.UpdateType != UpdatedAssignmentData.eUpdateType.Activated || IsActivated) data.Remove();
        }

        protected void ExportToExcel_Click(object sender, EventArgs e) { GridViewAssignments1.ExportToExcel(); }

        protected void ProduceForm_Tick(object sender, EventArgs e) 
        {
            ProduceFormTimer.Enabled = false;
            if (IsActivated)
            {
                IsActivated = false;
                return;
            }
            using (TempEmpDatabaseDataContext db = DbServices.db)
            {
                Assignment assignment = db.Assignments.Where((a) => a.ID == ActivatedID).First();
                ActivatedID = 0;
                IsActivated = true;
                assignment.ProduceForm();
            }
        }
    }

    internal class SearchAssignmentsStoreData : APageData
    {
        public int DropDownStatusIndex { get; private set; }
        public int DropDownUsersIndex { get; private set; }
        public int DropDownBudgetTypeIndex { get; private set; }

        public SearchAssignmentsStoreData(int dropDownStatusIndex, int dropDownUsersIndex, int dropDownBudgetTypeIndex)
        {
            DropDownStatusIndex = dropDownStatusIndex;
            DropDownUsersIndex = dropDownUsersIndex;
            DropDownBudgetTypeIndex = dropDownBudgetTypeIndex;
        }
    }

    public class UpdatedAssignmentData : APageData
    {
        public enum eUpdateType
        {
            New,
            Update,
            Approved,
            Activated,
            Rejected
        }

        public int AssignmentId { get; private set; }
        public eUpdateType UpdateType { get; private set; }

        public UpdatedAssignmentData(int assignmentId, eUpdateType updateType)
        {
            AssignmentId = assignmentId;
            UpdateType = updateType;
        }
    }
}

